package com.takanafu.haru{
	import com.takanafu.haru.code.CodeBase;
	import com.takanafu.haru.code.CodeINT;
	import com.takanafu.haru.code.UseCallback;
	import com.takanafu.haru.exp.AssignExpression;
	
	import flash.display.MovieClip;
	import flash.events.Event;
	
	import mx.events.CloseEvent;
	
	public class Thread extends MovieClip{
		private var code:String = null;
		private var lex:Lexer = null;
		private var parser:Parser = null;
		private var processing:Boolean = false;
		private var waitingCodeBase:CodeBase = null;
		
		static private var th:Thread; 
		
		public function Thread(val:String){
			super();
			
			th = this;
			this.code = val;
			this.lex = new Lexer(val);
			this.parser = new Parser();
			this.addEventListener(Event.ENTER_FRAME,onEnterFrame);
		}
		
		public var onEnterFrame:Function = function(event:Event):void{
			if(processing == false){
				processing = true;
				var cd:CodeBase = parser.parse(lex);
				
				if(cd == null){
					th.removeEventListener(Event.ENTER_FRAME,onEnterFrame);
					return;
				}
				cd.thread = th;
				var res:CodeBase = cd.run();
				
				if(res is UseCallback){
					waitingCodeBase = cd;
				}else{
					processing = false;
				}
			}else if(event.type != Event.ENTER_FRAME && waitingCodeBase != null){
				var ae:AssignExpression = waitingCodeBase as AssignExpression;
				
				if(ae != null){
					var evt:CloseEvent = event as CloseEvent;
					 
					if(evt != null){
						ae.runAfterCallback(new CodeINT(evt.detail));
					}
				}
				waitingCodeBase = null;
				processing = false;
			}
		}
	}
}